﻿using System;
using System.Linq;
using System.Windows.Data;
using SoftSource.Timecard.Web.Data;

namespace SoftSource.Timecard.Entry.Converters
{
    public sealed class BillingFrequencyIDConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null && value is int)
            {
                int id = (int)value;

                var billingFrequency = App.Model.BillingFrequencies.Entities.SingleOrDefault(bf => bf.BillingFrequencyID == id);

                if (billingFrequency != null && parameter != null && parameter is string)
                {
                    string propertyName = (string)parameter;

                    var property = billingFrequency
                        .GetType()
                        .GetProperty(propertyName);

                    if (property != null)
                        return property.GetValue(billingFrequency, null);
                }
                else
                {
                    return billingFrequency;
                }
            }

            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null && value is BillingFrequency)
            {
                BillingFrequency frequency = (BillingFrequency)value;

                if (frequency != null)
                {
                    return frequency.BillingFrequencyID;
                }
            }

            return null;
        }

        #endregion
    }
}
